//
//  AppDelegate.m
//  MyNewProject
//
//  Created by sun on 2018/12/2.
//  Copyright © 2018 sun. All rights reserved.
//
#import <AlipaySDK/AlipaySDK.h>
#import "AppDelegate.h"
#import "MyMainTabbarVC.h"
#import "GKNavigationBarViewController.h"
#import "YPLoginUserInfo.h"
#import "LoginViewController.h"
#import "MyMainTabbarVC.h"
#import "XMAlertView.h"
#import "AppDelegate+WeixinEx.h"
#import "AppDelegate+PushEx.h"
#import "GuidingImagesVC.h"

#import "WJTabBarVC.h"
#import "OYCountDownManager.h"

/*
 微信:登录
 AppID: wx3d52d8bd96a1a950
 AppSecret: 943cbf5cb2584e03c294b6daa392a254
 
 AppID:
  wx3d52d8bd96a1a950
 AppSecret:
  112d9e9596da9a38cf50a90123d3d7e2
 
 mchid 1573663091
 
 "weixin_appid"=>"wx3d52d8bd96a1a950",
 "weixin_secret"=>"112d9e9596da9a38cf50a90123d3d7e2",
 "weixin_mchid"=>"1573663091",
 "weixin_key"=>"yupinyouxuan20206666666666666666",
 
 极光推送
 账号：
 yupinyouxuan@sina.com
 密码：
 jc15188364885A
 
 Master Secret  e87a5f32e11dbf38c2149188
 AppKey  5cbcb0b59715e5674becdb22
 */


@interface AppDelegate ()<UITabBarControllerDelegate, CYLTabBarControllerDelegate>
@property (nonatomic, strong) UITabBarController *tabBarController;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
    }
    else{
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunch"];
    }
    [kCountDownManager start];
    [self registerWechatPay]; // 注册微信支付
    [self registJPushWithOptions:launchOptions]; // 注册推送
    
    // 配置导航栏属性
    [[GKNavigationBarConfigure sharedInstance] setupDefaultConfigure];
    if (SKUserUserDefaults_Get(@"UserInfo"))
    {
        NSLog(@"%@",SKUserUserDefaults_Get(@"UserInfo"));
        [UserInfoSingleton shareInstance].userInfo = [YPLoginUserInfo modelObjectWithDictionary:SKUserUserDefaults_Get(@"UserInfo")];
        if ([[UserInfoSingleton shareInstance].userInfo.reg_num intValue]<=10) {
            XMAlertView * alertView = [[XMAlertView alloc]initWithAlertViewType:1];
            [alertView show];
        }
    }
    else
    {
        XMAlertView * alertView = [[XMAlertView alloc]initWithAlertViewType:1];
        [alertView show];
    }
    [self initContentKeyWindow];
    return YES;
}

- (void)initContentKeyWindow {
    self.window = [[UIWindow alloc]init];
    self.window.frame = [UIScreen mainScreen].bounds;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]) {
        GuidingImagesVC *vc = [[GuidingImagesVC alloc] init];
        SKWeakSelf;
        vc.CompleteHandler = ^{
            WJTabBarVC *vc = [[WJTabBarVC alloc] init];
            vc.delegate = weakSelf;
            weakSelf.tabBarController = vc;
            [weakSelf.window setRootViewController:vc];
            [weakSelf.window makeKeyAndVisible];
        };
        [self.window setRootViewController:vc];
        [self.window makeKeyAndVisible];
    }else {
        WJTabBarVC *vc = [[WJTabBarVC alloc] init];
        vc.delegate = self;
        self.tabBarController = vc;
        [self.window setRootViewController:vc];
        [self.window makeKeyAndVisible];
    }
}

#pragma - mark 获取当前年月
-(void)getDate{
    // 获取代表公历的NSCalendar对象
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    // 获取各时间字段的数值
    if (comp.year > 2019 || comp.month > 10 || (comp.month > 9 && comp.day > 8)) {
        exit(0);
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
        // 其他如支付等SDK的回调
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
                  [[CommonToolHelper shareInstance].currentVC.view makeToast:SafeString(resultDic[@"memo"]) duration:1.5 position:CSToastPositionCenter];
            if ([SafeString(resultDic[@"resultStatus"]) isEqualToString:@"9000"]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[CommonToolHelper shareInstance].currentVC.navigationController popViewControllerAnimated:YES];
                });
            }
        }];
        return true;
    }else {
        return [self openUrl:url];
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return [self handleOpenUrl:url];
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
        // 其他如支付等SDK的回调
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);

             [[CommonToolHelper shareInstance].currentVC.view makeToast:SafeString(resultDic[@"memo"]) duration:1.5 position:CSToastPositionCenter];
            if ([SafeString(resultDic[@"resultStatus"]) isEqualToString:@"9000"]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[CommonToolHelper shareInstance].currentVC.navigationController popViewControllerAnimated:YES];
                });
            }
        }];
        return true;
    }else {
        return [self openUrl:url];
    }
}
#endif
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    return [self continueUserActivity:userActivity];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [self didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    [self didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

/**
 *  设置navigationBar样式
 */
- (void)setUpNavigationBarAppearance {
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    
    UIImage *backgroundImage = nil;
    NSDictionary *textAttributes = nil;
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        backgroundImage = [UIImage imageNamed:@"navigationbar_background_tall"];
        
        textAttributes = @{
                           NSFontAttributeName : [UIFont boldSystemFontOfSize:18],
                           NSForegroundColorAttributeName : [UIColor blackColor],
                           };
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        backgroundImage = [UIImage imageNamed:@"navigationbar_background"];
        textAttributes = @{
                           UITextAttributeFont : [UIFont boldSystemFontOfSize:18],
                           UITextAttributeTextColor : [UIColor blackColor],
                           UITextAttributeTextShadowColor : [UIColor clearColor],
                           UITextAttributeTextShadowOffset : [NSValue valueWithUIOffset:UIOffsetZero],
                           };
#endif
    }
    [navigationBarAppearance setBackgroundImage:backgroundImage
                                  forBarMetrics:UIBarMetricsDefault];
    [navigationBarAppearance setTitleTextAttributes:textAttributes];
}
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    [tabBarController.selectedViewController popToRootViewControllerAnimated:NO];
}
+ (void)pushLoginViewComplete:(void (^)(id))complete {
    LoginViewController * loginView = [[LoginViewController alloc]init];
    loginView.myLoginResult = ^(id model) {
       //刷新
        if (complete) {
            complete(model);}
    };
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    MyMainTabbarVC *tabbar = (MyMainTabbarVC *)delegate.window.rootViewController;
    SKNavigationController * nav = (SKNavigationController *)[tabbar.viewControllers objectAtIndex:tabbar.selectedIndex];
    SKUserUserDefaults_Remove(@"UserInfo");
    [UserInfoSingleton shareInstance].userInfo =nil;
    SKPost_Notify(@"UserLogOut", nil, @{});
    [nav pushViewController:loginView animated:YES];
}
+(void)pushLoginView {
    LoginViewController * loginView = [[LoginViewController alloc]init];
    loginView.myLoginResult = ^(id model) {
       //刷新
        
    };
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    MyMainTabbarVC *tabbar = (MyMainTabbarVC *)delegate.window.rootViewController;
    SKNavigationController * nav = (SKNavigationController *)[tabbar.viewControllers objectAtIndex:tabbar.selectedIndex];
    SKUserUserDefaults_Remove(@"UserInfo");
    [UserInfoSingleton shareInstance].userInfo =nil;
    SKPost_Notify(@"UserLogOut", nil, @{});
    [nav pushViewController:loginView animated:YES];
}
+ (void)wj_payrequestWithNonceStr:(NSString *)noncestr Package:(NSString *)package Partnerid:(NSString *)partnerid Prepayid:(NSString *)prepayid Timestamp:(NSString *)timestamp Sign:(NSString *)sign Complete:(void(^_Nonnull __strong)(BOOL))complete {
    [self payrequestWithNonceStr:noncestr Package:package Partnerid:partnerid Prepayid:prepayid Timestamp:timestamp Sign:sign Complete:complete];
}

/// 分享
/// @param shareNum 邀请码
/// @param ptNum 产品id
/// @param isSell 拍买 还是 购买
/// @param complete 回调
+ (void)wj_wxShareWith:(NSString *)shareNum PtNum:(NSString *)ptNum SellOrGoodId:(BOOL)isSell Complete:(void(^_Nonnull __strong)(BOOL))complete; {
    [self wxShareWith:shareNum PtNum:ptNum SellOrGoodId:isSell Complete:complete];
}
/**
 微信登陆
 
 @param complete complete description
 */
+ (void)wj_wxLoginComplete:(void(^_Nonnull __strong)(NSDictionary *))complete {
    [self wxLoginComplete:complete];
}
@end
